package controller

import (
	"editor/constant"
	"editor/service/mdFile"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
	"net/http"
)

func IndexHandler(c *gin.Context) {
	newList, err := mdFile.GetListItemWithDir(c)
	if err != nil {
		c.Writer.WriteHeader(http.StatusOK)
		_, _ = c.Writer.Write([]byte("get file list failed, error:" + err.Error()))
		return
	}

	id := cast.ToInt64(c.Param("id"))
	if id <= 0 {
		id = mdFile.GetDefaultId(newList)
		if id <= 0 {
			c.Writer.WriteHeader(http.StatusOK)
			_, _ = c.Writer.Write([]byte("get default id empty"))
			return
		}
		c.Writer.WriteHeader(http.StatusFound)
		c.Writer.Header().Set("Location", fmt.Sprintf("/read/%d", id))
		return
	}

	info, err := mdFile.GetMDFileInfo(c, id)
	if err != nil {
		c.Writer.WriteHeader(http.StatusOK)
		_, _ = c.Writer.Write([]byte("get markdown file info failed"))
		return
	}
	if info == nil {
		c.Writer.WriteHeader(http.StatusOK)
		_, _ = c.Writer.Write([]byte("markdown file info empty"))
		return
	}

	c.HTML(http.StatusOK, "index.html", gin.H{
		"Title":      info.MdTitle,
		"Content":    info.MdContent,
		"FileList":   newList,
		"CurId":      info.ID,
		"CurrentDir": info.CategoryID,
		"User":       c.GetString(constant.UserName),
	})
}
